//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <mantle.h>

PInterface CHostingManager::Probe(
    /* [in] */ REIID riid)
{
    if (riid == EIID_IInterface) {
        return (PInterface)(IHostingManager *)this;
    }
    else if (riid == EIID_IHostingManager) {
        return (IHostingManager *)this;
    }
    else if (riid == EIID_CLASS_INFO) {
        return (PInterface)&ECLSID_CHostingManager;
    }
    else if (riid == EIID_INTERFACE_INFO) {
        return (PInterface)&EIID_IHostingManager;
    }

    return NULL;
}

UInt32 CHostingManager::AddRef(void)
{
    return 3;
}

UInt32 CHostingManager::Release(void)
{
    return 2;
}

ECode CHostingManager::Aggregate(
    /* [in] */ AggregateType type,
    /* [in] */ PInterface pObj)
{
    return E_NOT_IMPLEMENTED;
}

ECode CHostingManager::GetDomain(
    /* [out] */ PInterface *ppObj)
{
    return E_NOT_IMPLEMENTED;
}

ECode CHostingManager::GetOne(
    /* [out] */ IAppletHosting ** ppHost)
{
    WaitResult wr;
    ECode ec;
    CProcess *pProc;

    pProc = new CProcess;
    if (NULL == pProc) return E_OUT_OF_MEMORY;
    pProc->AddRef();

    m_hostLock.Lock();
    m_hostEvent.Clear();

    ec = pProc->Start(L"SuperExe.exe", L"-Hosting");
    if (FAILED(ec)) goto ErrorExit;

    m_hostEvent.TryWait(c_nWaitHostTimeout, &wr, (EventState *)ppHost);
    if ((WaitResult_OK == wr) && (NULL != *ppHost)) {
        (*ppHost)->AddRef();
    }
    else {
        ec = E_TIMED_OUT;
    }

ErrorExit:
    m_hostLock.Unlock();

    pProc->Release();
    return ec;
}

ECode CHostingManager::Register(
    /* [in] */ IAppletHosting * pHost)
{
    if (NULL == pHost) {
        return E_INVALID_ARGUMENT;
    }

    pHost->AddRef();
    m_hostEvent.Notify((EventState)pHost);
    return NOERROR;
}

ECode CHostingManager::Unregister(
    /* [in] */ IAppletHosting * pHost)
{
    if (NULL != pHost) {
        pHost->Release();
    }
    return NOERROR;
}
